package com.xxxx.yoyo.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xxxx.yoyo.bean.Goods;
import com.xxxx.yoyo.bean.Item;
import com.xxxx.yoyo.bean.Order;
import com.xxxx.yoyo.bean.User;
import com.xxxx.yoyo.service.IGoodsService;
import com.xxxx.yoyo.service.IOrderService;
import com.xxxx.yoyo.service.impl.GoodsServiceImpl;
import com.xxxx.yoyo.service.impl.OrderServiceImpl;

/**
 * Servlet implementation class AddToCartServlet
 */
@WebServlet("/index/addToCart")
public class AddToCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private IGoodsService goodsService = new GoodsServiceImpl();
	private IOrderService orderService = new OrderServiceImpl();
	
	
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//可以返回以下内容
		// ok  表示加入购物车成功
		// empty 要加入购物车的宠物库存不足
		// login 用户尚未登录
		// 其他内容   请求失败
		
		//如果用户尚未登录,我们返回login
		//查看session是否有user, 有的话,说明用户登录了, 没有的话,说明用户没有登录
		//(1)获取session
		HttpSession session = request.getSession();
		//(2)从session获取user
		User user = (User)session.getAttribute("user");
		if(user == null) {//session没有user, 说明用户没有登录
			response.getWriter().append("login");
		}else {//说明,用户已经登录过了
			//获取前端传递过来的参数goodid
			String goodsIdStr = request.getParameter("goodid");
			//把字符串转换为整型
			int goodsId = Integer.parseInt(goodsIdStr);
			
			//根据宠物的id查询宠物
			Goods goods = goodsService.getGoodsById(goodsId);
			//获取宠物的库存
			int stock = goods.getStock();
			if(stock <= 0) {//如果库存数量小于等于0, 说明库存不足
				response.getWriter().append("empty");
			}else {//库存充足---加入购物车
				//查看session中是否有虚拟订单(购物车信息)
				Order tempOrder = (Order)session.getAttribute("order");
				if(tempOrder == null) {//session没有order
					//创建虚拟订单
					tempOrder = new Order();
					//设置订单的下单用户id
					tempOrder.setUserId(user.getId());
					//创建一个列表,存放购买项(Item)
					List<Item> itemList = new ArrayList<>();
					//把空的列表项设置给虚拟订单. 方便以后添加购买项
					tempOrder.setItemList(itemList);
					//设置购物车宠物总数量为0
					tempOrder.setAmount(0);
					//设置购物车总金额为0.0
					tempOrder.setTotal(0.0);
					//把order存入session, 下一次点击加入购物车的时候session就有order. 
					session.setAttribute("order", tempOrder);
				}
				
				//把要购买的宠物(goods)加入虚拟订单(tempOrder)-----orderService
				orderService.addGoodsToOrder(goods, tempOrder);
				//返回添加成功
				response.getWriter().append("ok");
			}
		}
	}

}
